package com.example.fairplay.newfpregistration.fragments;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.fairplay.newfpregistration.R;
import com.example.fairplay.newfpregistration.camera.CameraInterface;
import com.example.fairplay.newfpregistration.camera.FacePicInterface;
import com.example.fairplay.newfpregistration.camera.FragmentCamera;
import com.example.mylibrary.activity.BaseFragment;
import com.example.mylibrary.data.ByteImg;
import com.example.mylibrary.data.DBManager;
import com.example.mylibrary.data.DataDao;
import com.example.mylibrary.data.StudentInfo;
import com.example.mylibrary.util.ThreadManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.com.aratek.facelib.AraFaceAuthLib;
import cn.com.aratek.idcard.IDCard;
import cn.com.aratek.idcard.IDCardReader;
import cn.com.aratek.util.Result;

/**
 * Created by fairplay on 2018/6/1.
 * 人脸识别fragment
 */

public class FaceToFaceFragment extends BaseFragment implements FacePicInterface {
    @Bind(R.id.imageView)
    ImageView imageView;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.ed_name)
    EditText edName;
    @Bind(R.id.ly_name)
    LinearLayout lyName;
    @Bind(R.id.tv_nation)
    TextView tvNation;
    @Bind(R.id.ed_nation)
    EditText edNation;
    @Bind(R.id.ly_nation)
    LinearLayout lyNation;
    @Bind(R.id.tv_birthday)
    TextView tvBirthday;
    @Bind(R.id.ed_birthday)
    EditText edBirthday;
    @Bind(R.id.ly_birthday)
    LinearLayout lyBirthday;
    @Bind(R.id.tv_school)
    TextView tvSchool;
    @Bind(R.id.ed_school)
    EditText edSchool;
    @Bind(R.id.ly_school)
    LinearLayout lySchool;
    @Bind(R.id.tv_sex)
    TextView tvSex;
    @Bind(R.id.ed_sex)
    EditText edSex;
    @Bind(R.id.ly_sex)
    LinearLayout lySex;
    @Bind(R.id.tv_idcard)
    TextView tvIdcard;
    @Bind(R.id.ed_idcard)
    EditText edIdcard;
    @Bind(R.id.ly_idcard)
    LinearLayout lyIdcard;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.ed_address)
    EditText edAddress;
    @Bind(R.id.ly_address)
    LinearLayout lyAddress;
    @Bind(R.id.tv_stuID)
    TextView tvStuID;
    @Bind(R.id.ed_stuID)
    EditText edStuID;
    @Bind(R.id.ly_stuID)
    LinearLayout lyStuID;
    @Bind(R.id.iv_face1)
    ImageView ivFace1;
    @Bind(R.id.iv_face2)
    ImageView ivFace2;
    @Bind(R.id.iv_face3)
    ImageView ivFace3;
    private View mView;

    private static final int MSG_FP_RESULT = 0;
    private static final int MSG_SHOW_INFO = 1;
    private static final int MSG_CARD_SUCESS = 2;
    private static final int MSG_SHOW_PROGRESS_DIALOG = 3;
    private static final int MSG_DISMISS_PROGRESS_DIALOG = 4;
    private static final int MSG_FACE_RESULT = 5;
    private StudentInfo mStudentInfo;
    private IDCard idCard;
    private byte[] cardData;
    private IDCardReader mReader;
    private boolean isReading = true;
    private String stuCode;//身份证号
    private byte[] snapshotFeature;//图像数组
    private byte[] fpbytes;//指纹数组
    private Bitmap cardBitmap;
    private StudentInfo studentInfo;
    private ReadThread readThread;
    private AraFaceAuthLib araFaceAuthLib;
    private List<ByteImg> byteImgs=new ArrayList<>();


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_CARD_SUCESS:
                    IDCard idCard = (IDCard) msg.obj;
                    stuCode = idCard.getNumber();
                    studentInfo = DBManager.getInstance(mActivity).queryStudentId(stuCode);
                    fpbytes = idCard.getFingerprint();
                    cardBitmap = idCard.getPhoto();
                    if(studentInfo!=null) {
                        tvName.setText(studentInfo.getStudentName() != null ? studentInfo.getStudentName() : "");
                        tvAddress.setText(studentInfo.getAddress() != null ? studentInfo.getAddress() : "");
                        tvBirthday.setText(studentInfo.getBirthday() != null ? studentInfo.getBirthday() : "");
                        tvSex.setText(studentInfo.getSex() == 0 ? "男" : "女");
                        tvNation.setText(studentInfo.getNation() != null ? studentInfo.getNation() : "");
                        tvIdcard.setText(studentInfo.getIdCard() != null ? studentInfo.getIdCard() : "");
                        tvIdcard.setText(studentInfo.getStudentID() != null ? String.valueOf(studentInfo.getStudentID()) : "");
                        tvIdcard.setText(studentInfo.getSchool() != null ? studentInfo.getSchool() : "");
                    }
                    ivFace1.setImageBitmap(cardBitmap);
                    //渲染数据
                    break;
            }
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_face_to_face, container, false);
        ButterKnife.bind(this, mView);
        initObjects();
        initViews();
        initData();
        setListeners();
        return mView;
    }

    @Override
    protected void findViews() {

    }

    @Override
    protected void initObjects() {
        mReader = IDCardReader.getInstance(mActivity);
        //   araFaceAuthLib= MainMenu.getAraFaceAuthLib();

    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void setListeners() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);

    }

    @Override
    public void onResume() {
        super.onResume();
        openDevice();

    }

    //开启线程
    private void readCard() {
        isReading = true;
        if (readThread == null) {
            readThread = new ReadThread();
            readThread.start();
        }
    }

    /**
     * 跳转人脸页面
     */
    private void faceResult(){
        byteImgs = DataDao.imgAll();
        for (int i = 0; i< byteImgs.size(); i++){
            ByteImg byteImg=new ByteImg();
            byteImg = byteImgs.get(i);
            if(byteImg.getByteImg() !=null){
                cardData = byteImg.getByteImg();
                byteImg.setByteImg(cardData);
                byteImg.setImgId(byteImgs.get(i).getImgId());
                byteImgs.add(byteImg);
            }
        }
        CameraInterface.setVerifyCount(5);


    }
    /**
     * 打开身份证设备
     */
    private void openDevice() {
        ThreadManager.getInstance().submit(new Runnable() {
            @Override
            public void run() {
                int error = 0;
                // DialogTools.showDialog(mActivity,getString(R.string.preparing_device));
                if ((error = mReader.powerOn()) != IDCardReader.RESULT_OK) {
                    // ToastUtils.Toast(mActivity,getString(R.string.id_card_reader_power_on_failed));
                    //DialogTools.dismssDialog();
                    return;
                }
                if ((error = mReader.open()) != IDCardReader.RESULT_OK) {
                    //ToastUtils.Toast(mActivity,getString(R.string.id_card_reader_open_failed));
                    //DialogTools.dismssDialog();
                    return;
                }
                //DialogTools.dismssDialog();
                // ToastUtils.Toast(mActivity,getString(R.string.device_open_success));
                readCard();
            }
        });
    }

    //识别身份证线程
    private class ReadThread extends Thread {
        public void run() {
            Result res;
            do {
                res = mReader.read();
            } while (res.error != IDCardReader.RESULT_OK && isReading == true);
            if (res.error == IDCardReader.RESULT_OK) {
                // ToastUtils.Toast(mActivity,getString(R.string.id_card_read_success));
                mHandler.sendMessage(mHandler.obtainMessage(MSG_CARD_SUCESS, (IDCard) res.data));
                idCard = (IDCard) res.data;
                final Result temp = res;

                //clearFeature();
                stuCode = idCard.getNumber();
                //将查询到的数据给数组
                stopReading();

            } else {

            }
        }

    }

    private void stopReading() {
        isReading = false;
        readThread = null;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeDevice();
    }

    /**
     * 关闭device
     */
    private void closeDevice() {
        new Thread() {
            @Override
            public void run() {
                int error;
                isReading = false;
                readThread = null;
                if ((error = mReader.close()) != IDCardReader.RESULT_OK) {
                    //   showInfoToast(getString(R.string.id_card_reader_close_failed));
                    //  DialogTools.dismssDialog();
                    return;
                }
                if ((error = mReader.powerOff()) != IDCardReader.RESULT_OK) {
                    //  showInfoToast(getString(R.string.id_card_reader_power_off_failed));
                    //  DialogTools.dismssDialog();
                    return;
                }

                // ToastUtils.Toast(mActivity,getString(R.string.device_close_success));
            }
        }.start();
    }

    @Override
    public void fromPic(int requestCode, int resultCode, Intent data) {
        if (requestCode == 222 && resultCode == 1) {
            float score = data.getFloatExtra("score", 0);

        }
    }
}
